package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.util.ValueStack;
import entities.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author corneliugosa
 */
public class AuthorizeLogin implements Interceptor {

    @Override
    public void destroy() {
        System.out.println("Destroyed!");
    }

    @Override
    public void init() {
        System.out.println("Initialized!");
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception{
        Map<String, Object> session = invocation.getInvocationContext().getSession();
        Map<String, Object> context = invocation.getInvocationContext().getApplication();
        List<User> userList = (List<User>)context.get("userList");
        ValueStack valueStack = invocation.getInvocationContext().getValueStack();

        User user = (User) session.get("user");
        boolean found = false;
        
        if (session == null || session.get("logged") == null) {
            return "failure";
        } else if (userList != null) {
            for (User usr : userList) {
                System.out.println("User: " + usr.getUsername());
                if (usr.getUsername().equals(user.getUsername())) {
                    valueStack.set("message", "This user is already logged on a different machine!");
                    invocation.getInvocationContext().setValueStack(valueStack);
                    return "failure";
                }
            }    
        } 

        if (found) {
            valueStack.set("message", "This user is already logged in on a different machine!");
            invocation.getInvocationContext().setValueStack(valueStack);
            return "failure";
        } else {
            userList = new ArrayList<User>();
            userList.add(user);
            context.put("userList", userList);
            invocation.getInvocationContext().setApplication(context);
            try {
                invocation.invoke();
            } catch (Exception ex) {
                Logger.getLogger(AuthorizeLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return "failure";
    }
}
